import {
  getToken,
  getUserId,
  getUserName,
  getUserStatus,
  setToken,
  setUserId,
  setUserName,
  setUserPass,
  setUserRoles,
  setUserStatus
} from '@/libs/auth'
import deepClone from '@/libs/deepClone'
import type { ActionContext } from 'vuex'
import { getUserRoles } from '@/libs/auth'
import router from '@/router'
import { RouteRecordRaw } from 'vue-router'
import asyncRouters from '@/router/asyncRouters'
import { RootState } from '.'
import { checkIsPhone, logout } from '@/libs/toolkit'
import { requestAuthCode } from '@/libs/dingding'
import { setSession } from '@/libs/sessionStorage'
import { getUserFunListByUserDDId } from '@/api/dd'
import { ant_design_vue } from '@/libs/global/antDesignVue'
let { message } = ant_design_vue

export type LoginState = {
  roles: number[]
  userName: string | null
  userId: string | null
  token: string | null
  userFuns: Pm.UserFun[]
}

export type LoginContext = ActionContext<LoginState, RootState>

export const state: LoginState = {
  roles: [0],
  userName: null,
  userId: null,
  token: null,
  userFuns: []
}

export const getters = {
  GETROLES(state: LoginState) {
    return state.roles
  },
  GETUSERID(state: LoginState) {
    return state.userId
  },
  GETUSERNAME(state: LoginState) {
    return state.userName
  },
  GETTOKEN(state: LoginState) {
    return state.token
  },
  userFuns: (state: LoginState) => state.userFuns
}
export const mutations = {
  SETROLES(state: LoginState, data: number[]) {
    state.roles = data
    setSession('userRoles', data)
  },
  SETUSERINFO_TOKEN(state: LoginState, data: string) {
    state.token = data
    setToken(data)
  },
  SETUSERINFO_USERNAME(state: LoginState, data: string) {
    state.userName = data
    setUserName(data)
  },
  SETUSERINFO_USERID(state: LoginState, data: string) {
    state.userId = data
    setUserId(data)
  },
  CLEARUSERINFO(state: LoginState, data: string) {
    state.userName = null
    state.userId = null
    state.token = null
  }
}

export type GetUserInfoReturnData = Promise<
  | {
    userInfo: User.Info
    userFuns: Pm.UserFun[]
  }
  | false
>

export const actions = {
  LOGIN({ commit, dispatch, rootState }: LoginContext, data: { userName: string; userPass: string }) {
    return new Promise(async (rep, rej) => {
      // dispatch('GenerateRoutes').then(res => {
      //   rep(true)
      // }).catch((err) => {
      //   console.log('路由信息加载失败', err);
      //   router.push('/login')
      //   rej(false)
      // })
    })
  },
  LOGOUT({ commit, dispatch }: LoginContext) {
    logout()
  },
  /**获取用户信息*/
  GetUserInfo: ({ state, commit, rootState, rootGetters, dispatch }: LoginContext) => {
    return new Promise(
      (
        resolve: (value: {
          userInfo: User.Info
          userFuns: Pm.UserFun[]
          userRoles: string[]
        }) => void,
        reject: (err: false) => void
      ) => {
        requestAuthCode()
          .then(userInfo => {
            commit('dingding/SETUSERINFO', userInfo, { root: true })

            setSession('userDDId', userInfo.userId)

            getUserFunListByUserDDId({ userDDId: userInfo.userId })
              .then(res => {
                // rootState.aside.userAsideList = res.data
                rootState.aside.userAsideList = []

                state.userFuns = res.data

                const parentPath = location.href
                  .replace(
                    /^(http|https|ws|wss):\/\/(\w+\.*)+\:?([0-9]{4})?(\/\#)?(\/\w+)?([\/|\w]*)(\?[\w|\=|\&]+)*/g,
                    '$5'
                  )
                  .substring(1)

                console.log('dingding actions requestAuthCode parentPath', parentPath)

                // 获取页面路由中的父路由
                rootState.aside.selectedKeys = [parentPath]

                /**不能在这里跳转，不然有些携带参数的路由会丢失参数 */
                // router.push({
                //   name: parentPath
                // })

                const userRoles = res.data.map(item => item.dictCode)

                commit('SETROLES', userRoles)

                resolve({ userInfo, userFuns: res.data, userRoles: userRoles })
              })
              .catch(err => {
                message.error({
                  content: '界面配置获取失败'
                })
                reject(false)
              })
          })
          .catch(err => {
            reject(false)
          })
      }
    )
  },
  /**筛选需要的路由 */
  GenerateRoutes: ({ commit, dispatch, rootGetters }: LoginContext) => {
    return new Promise<boolean>(async (resolve, reject) => {
      try {
        let isPhone = checkIsPhone()

        let routers = deepClone(asyncRouters)

        let userFuns = state.userFuns

        routers.map((data: RouteRecordRaw) => {

          const isCode = isPhone
            ? data.meta?.isPhoneLoad
            : userFuns.findIndex(
              item => item.dictCode === data.meta?.code && !data.meta.isPhoneLoad
            ) !== -1 || data.meta?.code === '0000'

          if (isCode) {
            router.addRoute(data.name || data.path.replace('/', '-').substring(1), data)
          }
        })

        console.log('路由加载完成', router.getRoutes())
        resolve(true)
      } catch (err) {
        console.log('路由信息加载失败', err)
        dispatch('LOGOUT').then(res => {
          reject(false)
        })
      }
    })
  }
}
export default {
  namespaced: true, // 声明命名空间
  state,
  mutations,
  actions,
  getters
}
